import os, uuid, re, json, time, datetime
from django.core.cache import cache
from django.contrib.auth.hashers import make_password, check_password
from django.core.mail import send_mail
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
import django.utils.timezone as timezone
from .models import *
from SuperApplication import settings
from django.contrib import messages
from .CommonFunction import *
import json
import pandas as pd

# Create your views here.


def index(request):
    # code = cache.get('')
    return HttpResponse("codase")
# 头像，用户名加载
def img_loading(request):
    response = {}
    phone = request.session.get('phone_num')
    user = spi_User.objects.get(user_phone=phone)
    res = spi_resume.objects.get(user=user)
    response['avatar_url'] = res.resume_avatar_url
    response['user_name'] = user.user_name
    response['user_id'] = user.pk
    return JsonResponse(response)

# 应聘信息取消
def ru_delete(request):
    response = {}
    ru_id = None
    if request.method == "POST":
        result = json.loads(bytes.decode(request.body))
        ru_id = result.get('ru_id')
    try:
        spi_UserCompanyInfo.objects.get(pk=int(ru_id)).delete()
        response['case'] = 'ok'
    except:
        response['case'] = 'no'
    return  JsonResponse(response)

# 应聘信息展示
def job_load(request):
    data_list = []
    data_json = {}
    phone = request.session.get('phone_num')
    user = spi_User.objects.get(user_phone=phone)
    res_user_infos = spi_UserCompanyInfo.objects.filter(User=user)
    for res_user_info in res_user_infos:
        res = spi_RecruitmentInfo.objects.get(pk=int(res_user_info.REC_id))
        rc = spi_RecruitmentCompany.objects.get(pk=int(res.Company_id))
        data_list.append({
            'ru_id': res_user_info.pk, 'rec_id': res.pk, 'rec_name': res.REC_Name, 'rec_wage': res.REC_Wage,
            'rec_PostAsk': res.REC_PostAsk, 'rec_address': res.REC_Address, 'rc_name': rc.RC_Name,
            'rc_scale': rc.RC_Scale, 'rc_financing': rc.RC_Financing, 'rc_label': rc.RC_Label
        })
    data_json['data_list'] = data_list
    data_json['total'] = len(res_user_infos)
    if len(res_user_infos) > 0:
        data_json['state'] = 'ok'
    else:
        data_json['state'] = 'no'

    return JsonResponse(data_json)

# 应聘
def job(request):
    response = {}
    red_id = None
    phone = None
    if request.method == 'POST':
        result = json.loads(bytes.decode(request.body))
        red_id = result.get('red_id')
        phone = result.get('phone_num')
    try:
        user = spi_User.objects.get(user_phone=phone)
        rec = spi_RecruitmentInfo.objects.get(pk=red_id)
        uc_info = spi_UserCompanyInfo()
        uc_info.type = 0
        uc_info.User = user
        uc_info.REC = rec
        uc_info.save()
        mail_manage(rec.REC_Name, user.user_name)
        response['job_case'] = 'ok'
    except:
        response['job_case'] = 'no'
    return JsonResponse(response)
# 邮箱信息发送
def mail_manage(rec_name, user_name):

    msg = '您好！贵公司的招聘的{0}(岗位)收到了{1}(应聘者)的简历,' \
          '请尽快上线查看以及给予反馈。谢谢'.format(rec_name, user_name)
    yourMail = ['1953860600@qq.com']
    send_mail(
        '超聘',
        msg,
        settings.EMAIL_HOST_USER,
        yourMail,
        # fail_silently=False,
    )
    print('发送完成')

#  搜索框检索函数 #
def search(request):
    search_txt = 'java'
    re_list = list()
    page_num = ''
    data_json = {}
    if request.method == 'POST':
        result = json.loads(bytes.decode(request.body))
        search_txt = result.get('search_txt')
        page_num = result.get('page_num')
        if page_num == '':
            page_num = 0
    if search_txt:
        # 模糊查询
        oo = spi_RecruitmentInfo.objects.filter(REC_Name__contains=search_txt)
        oi = spi_RecruitmentInfo.objects.filter(REC_PostAsk__contains=search_txt)
        coms = spi_RecruitmentCompany.objects.filter(RC_Name__contains=search_txt)
        for com in coms:
            t = spi_RecruitmentInfo.objects.filter(Company=com)
            oo = oo | t
        o = oo | oi
        page_size = settings.PAGE_SIZE
        sta = int(page_num) * page_size
        end = sta + page_size
        # print(o[sta:end])
        for i in o[sta:end]:
            re_list.append(
                {'REC_pk': i.pk, 'REC_Name': i.REC_Name, 'REC_Wage': i.REC_Wage, 'REC_Address': i.REC_Address,
                 'RC_Name': i.Company.RC_Name, 'RC_Label': i.Company.RC_Label, 'RC_pk': i.Company_id})
            # 打印招聘信息
            print(i.REC_Name + '---' + i.REC_PostAsk + '---' + i.Company.RC_Name)
        if o:
            data_json['data_list'] = re_list
            data_json['total'] = len(o)
            data_json['data_case'] = 'ok'
        else:
            data_json['data_case'] = 'no'
    return JsonResponse(data_json)


# 简历页面数据
def res_display(request):
    response = {}
    phone = None
    # phone = 17623310911
    if request.method == 'POST':
        result = json.loads(bytes.decode(request.body))
        phone = result.get('phone_num')
    try:
        user = spi_User.objects.get(user_phone=phone)
        user_json = spi_User.objects.values().get(user_phone=phone)
        resume = spi_resume.objects.get(user=user)
        resume_json = spi_resume.objects.values().get(user=user)
        works = spi_workExperience.objects.filter(reume=resume)
        response['res_case'] = 'ok'
        response['user'] = [user_json]
        response['resume_list'] = [resume_json]
        response['works'] = list(works.values())
    except:
        response['res_case'] = 'no'
    print(response)
    return JsonResponse(response)

# 信息处理--导入mysql数据库
def data_cl(request):
    lie = pd.read_csv('spiAPP/static/Jobs.csv', encoding='utf-8')
    da = []
    for i in lie.index:
        data_list = []
        for j in lie.loc[i]:
            data_list.append(j)
        da.append(data_list)
    print(len(da), len(lie))
    for i in da[1180:]:
        print(type(i), len(i), i)
        try:
            rc = spi_RecruitmentCompany.objects.get(RC_Name=str(i[4][:20]))
        except:
            rc = spi_RecruitmentCompany()
            rc.RC_Name = i[4][:20]
            rc.RC_Scale = i[2][:20]
            rc.RC_Address = i[-1][:20]
            k0 = ' '
            for j in i[3].split():
                k0 += str(j)
            rc.RC_Synopsis = k0
            rc.RC_Financing = '未融资'
            rc.RC_Label = i[6][:20]
            rc.RC_BusinessScope = i[5][:20]
            rc.RC_RegisteredCapital = '2000万'
            rc.RC_RegisteredTime = '2015-1-20'
            rc.save()
            rc = spi_RecruitmentCompany.objects.get(RC_Name=str(i[4][:20]))
        rec = spi_RecruitmentInfo()
        rec.REC_Name = i[-3][:30]
        rec.REC_ReleaseTime = '2020-' + str(re.findall(r"(.*?)发布", i[7])[0])
        k1 = ''
        for j in i[10].split():
            k1 += str(j)
        rec.REC_PostDescription = k1
        rec.REC_PostAsk = i[-2][:50]
        rec.REC_Address = i[8][:10]
        rec.REC_Type = i[2][:30]
        rec.REC_Wage = i[-4][:20]
        rec.Company = rc
        rec.save()
        print('{0}--插入完成'.format(i[-3]))
    return HttpResponse('ok')

# 保存简历页面数据
def res_save(request):
    response = {}
    ruleForm = None
    phone = None
    if request.method == 'POST':

        result = json.loads(request.body.decode())
        ruleForm = result.get('ruleForm')

        phone = request.session.get('phone_num')
    try:
        user = spi_User.objects.get(user_phone=phone)
        user.user_name = ruleForm['name']
        user.user_mail = ruleForm['email']
        user.save()

        res = spi_resume.objects.get(user=user)
        res.resume_census = ruleForm["address"]
        if ruleForm["gender"] == '女':
            res.resume_age = True
        else:
            res.resume_age = False
        res.resume_birthday = str(ruleForm["birthday"][:10])
        res.resume_state = ruleForm["state"]
        res.resume_nationality = ruleForm['nationality']
        res.resume_SchoolLevel = ruleForm['education']
        res.resume_School = ruleForm['school_name']
        res.resume_professional = ruleForm['major']
        res.resume_GraduationTime = str(ruleForm['Graduation_time'][:10])
        res.resume_hope_position = ruleForm['position']
        res.resume_hope_annuity = ruleForm['salary']
        res.resume_hope_location = ruleForm['location']
        res.resume_hope_industry = ruleForm['industry']
        res.save()
        spi_workExperience.objects.filter(reume=res).delete()
        if ruleForm['works_exp']:
            for work in ruleForm['works_exp']:
                print(work)
                print(type(work))
                wok = spi_workExperience()
                wok.reume = res
                wok.We_CompanyName = work['We_CompanyName']
                wok.We_EntryTime = str(work['We_EntryTime'][:10])
                wok.We_ResignTime = str(work['We_ResignTime'][:10])
                wok.We_ResponsibilityTxt = work['We_ResponsibilityTxt']
                wok.We_Number = work['We_Number']
                wok.We_location = work['We_location']
                wok.We_PositionType = work['We_PositionType']
                wok.We_PositionName = work['We_PositionName']
                wok.We_CompanyIndustry = work['We_CompanyIndustry']
                wok.save()
                response["save_case"] = 'ok'
        response["save_case"] = 'ok'
    except :
            response["save_case"] = 'no'
    return  JsonResponse(response)

# 附件上传
def upload_file(request):
    response = {}
    if request.method == 'POST':
        phone = request.session.get('phone_num')
        file = request.FILES.get('resumeFile')
        username = spi_User.objects.get(user_phone=phone).pk
        print(file.name)
        # 判断路径是否存在，如果不存在则创建路径
        head_path = settings.BASE_DIR + "\\media\\{}\\resume".format(username).replace(" ", "")
        print("head_path", head_path)
        if not os.path.exists(head_path):
            os.makedirs(head_path)
        # 图片后缀
        head_suffix = file.name.split(".")[-1]
        print("图片后缀", head_suffix)
        # 储存路径
        file_path = head_path + "\\{}".format("head." + head_suffix)
        file_path = file_path.replace(" ", "")
        print("储存路径", file_path)
        # 上传图片
        with open(file_path, 'wb+') as f:
            for chunk in file.chunks():
                f.write(chunk)
        back_path = '\\static\{}\\resume\\{}'.format(username, "resume." + head_suffix).replace(" ", "")
        response['upload_case'] = 'ok'
        response['back_path'] = back_path
    else:
        response['upload_case'] = 'no'
    return HttpResponse(response)

# 头像上传
def upload_img(request):
    response = {}
    img_type = ['jpg', 'png', 'tif', 'bmp', 'gif', 'webp']
    if request.method == 'POST':
        phone = request.session.get('phone_num')
        file = request.FILES.get('resumeFile')
        user = spi_User.objects.get(user_phone=phone)
        rec = spi_resume.objects.get(user=user)
        username = user.pk
        print(file.name)
        # 判断路径是否存在，如果不存在则创建路径
        head_path = settings.BASE_DIR + "\\media\\{}\\img".format(username).replace(" ", "")
        print("head_path", head_path)
        if not os.path.exists(head_path):
            os.makedirs(head_path)
        # 图片后缀
        head_suffix = file.name.split(".")[-1]
        print("图片后缀", head_suffix)
        if head_suffix in img_type:
            # 储存路径
            file_path = head_path + "\\{}".format("HeadPortrait." + head_suffix)
            file_path = file_path.replace(" ", "")
            print("头像储存路径", file_path)
            # 上传图片
            with open(file_path, 'wb+') as f:
                for chunk in file.chunks():
                    f.write(chunk)
            print(file_path.replace('\\', '/'))
            rec.resume_avatar_url = file_path.replace('\\', '/')
            rec.save()
            response['upload_case'] = 'ok'
            response['back_path'] = file_path
        else:
            response['upload_case'] = 'no'
    else:
        response['upload_case'] = 'no'
    return HttpResponse(response)

# 详情页面信息展示
def details(request):
    response = {}
    rec_id = None
    if request.method == 'POST':
        result = json.loads(bytes.decode(request.body))
        rec_id = result.get('rec_id')
    try:
        recs = spi_RecruitmentInfo.objects.get(pk=int(rec_id))
        rec = spi_RecruitmentInfo.objects.values().get(pk=int(rec_id))
        rc = spi_RecruitmentCompany.objects.values().get(pk=recs.Company.pk)
        response['rec_lists'] = rec
        response['rc_lists'] = rc
        response['detail_case'] = 'ok'
    except:
        response['detail_case'] = 'no'
    return JsonResponse(response)


# 用户信息接口
def user_info(request):
    # phone = None
    phone = 17623310987
    if request.method == 'POST':
        result = json.loads(bytes.decode(request.body))
        phone = result.get('phone_num')
    if phone:
        date = 0
        user = spi_User.objects.get(user_phone=phone)
        rms = spi_resume.objects.get(user=user)
        works = spi_workExperience.objects.filter(reume=rms)
        for work in works:
            a = work.We_EntryTime - work.We_ResignTime
            if a:
                date = date + int(str(a).split()[0])
            else:
                date = date + 0
        t = date / 365
        if t < 1:
            datelist = '工作经验小于1年'
        elif 1 <= t <= 3:
            datelist = '工作经验1至3年'
        elif 3 <= t <= 5:
            datelist = '工作经验3至5年'
        else:
            datelist = '工作经验5年以上'
        user_json = {'census': rms.resume_census, 'user_id': str(user.pk), 'user_name': user.user_name,
                     'datelist': datelist, 'img_url': rms.resume_avatar_url }
        print('用户信息：', user_json)
    return JsonResponse(user_json)


# 招聘信息加载及操作
def rec_operate(request):
    oo = ''
    response = {}
    page_num = ''
    data = list()
    if request.method == 'POST':
        result = json.loads(bytes.decode(request.body))
        page_num = result.get('page_num')
        if page_num == '':
            page_num = 0
        elif type(page_num) == int:
            page_num = page_num - 1
    oo = get_article(page_num)
    total = spi_RecruitmentInfo.objects.all().count()
    for i in oo:
        data.append({'REC_Name': i.REC_Name, 'REC_Wage': i.REC_Wage, 'REC_Address': i.REC_Address,
                     'REC_pk': i.pk, 'RC_Name': i.Company.RC_Name, 'RC_Label': i.Company.RC_Label,
                     'RC_pk': i.Company_id})
    print(data)
    response['data_json'] = data
    response['page_num'] = page_num + 1
    response['total'] = total
    return JsonResponse(response)


def get_article(page_index=0):
    page_size = settings.PAGE_SIZE
    sta = int(page_index) * page_size
    end = sta + page_size
    oo = spi_RecruitmentInfo.objects.all()[sta:end]
    return oo


# 登陆
def Login(request):
    response = {}
    if request.method == 'POST':
        # result = json.loads(request.body)
        result = json.loads(bytes.decode(request.body))
        phone_num = result.get('phone_num')
        number = result.get('phone_code')
        request.session['phone_num'] = phone_num
        response['login_case'] = 'off'
        try:
            q = spi_User.objects.get(user_phone=phone_num)
            if check_password(number, q.user_password):
                # if q.user_password == number:
                response['login_case'] = 'on'
                return JsonResponse(response)
            elif number == cache.get('phone_' + phone_num):
                response['login_case'] = 'on'
                return JsonResponse(response)
            else:
                return JsonResponse(response)
        except:
            if number == cache.get('phone_' + phone_num):
                response['login_case'] = 'on'
                return JsonResponse(response)
            else:
                return JsonResponse(response)
    else:
        return JsonResponse(response)


# 注册
@csrf_exempt
def register(request):
    response = {}
    if request.method == 'POST':
        result = json.loads(bytes.decode(request.body))
        print(result)
        name = result.get('name')
        gender = result.get('gender')
        birth_date = str(result.get('birth_date')[:10])
        email = result.get('email')
        identity = result.get('identity')  # 身份
        city = result.get('city')
        state = result.get('state')  # 求职状态
        # begin_date = result.get('begin_date')
        phone = request.session.get('phone_num')
        print(phone, type(phone))
        password = phone[8:11]
        if identity == '我是职场人':
            identity = 1
        elif identity == '我是学生':
            identity = 0
        if gender == '男':
            gender = False
        elif gender == '女':
            gender = True
        try:
            if spi_User.objects.filter(user_phone=phone):
                a = spi_User.objects.get(user_phone=phone)
                a.user_name = name
                a.user_mail = email
                a.save()
            else:
                a = spi_User(user_name=name, user_phone=phone, user_password=make_password(password), user_mail=email,
                             user_type=identity)
                a.save()

            user = spi_User.objects.get(user_phone=phone)
            if spi_resume.objects.filter(user=user):
                res = spi_resume.objects.get(user=user)
            else:
                res = spi_resume()
                res.user = user
            res.resume_age = gender
            res.resume_census = city
            res.resume_birthday = birth_date
            res.resume_state = state
            res.resume_nationality = 'x'
            res.resume_hope_location = 'x'
            res.resume_hope_annuity = 'x'
            res.resume_hope_industry = 'x'
            res.resume_hope_position = 'x'
            res.resume_School = 'x'
            res.resume_professional = 'x'
            res.resume_annuity = 'x'
            res.save()
            if identity == 1:
                response['register_case'] = 'ok1'
            else:
                response['register_case'] = 'ok0'
        except:
            response['register_case'] = 'no'
    return JsonResponse(response)


# 用户退出
def exit_user(request):
    request.session.clear()
    return JsonResponse({'exit_case': 'ok'})


# 工作经历写入
def work_set(request):
    response = {}
    if request.method == 'POST':
        result = json.loads(bytes.decode(request.body))
        name = result.get('componyname')  # 公司名称
        begin_date = str(result.get('begin_date')[:10])  # 工作开始时间
        end_date = str(result.get('end_date')[:10])  # 工作结束时间
        bumen = result.get('bumen')  # 部门
        value = result.get('value')[-1]  # 所属行业
        textarea = result.get('textarea')  # 工作职责
        position = result.get('position')  # 职位
        try:
            phone = request.session.get('phone_num')
            # user = spi_User.objects.get(user_phone=phone)
            user = spi_User.objects.filter(user_phone=phone).last()
            reume = spi_resume.objects.get(user=user)
            work = spi_workExperience()
            work.reume = reume
            work.We_CompanyName = name
            work.We_CompanyIndustry = value
            work.We_PositionName = position
            work.We_PositionType = bumen
            work.We_location = 'xx'
            work.We_Number = '0'
            work.We_EntryTime = begin_date
            work.We_ResignTime = end_date
            work.We_ResponsibilityTxt = textarea
            work.save()
            response['work_case'] = 'ok'
        except:
            response['work_case'] = 'no'
    return JsonResponse(response)


# 学校信息写入
def School_set(request):
    response = {}
    if request.method == 'POST':
        result = json.loads(bytes.decode(request.body))
        name = result.get('school_name')
        education = result.get('education')
        major = result.get('major')
        enddate = str(result.get('date1')[:10])
        phone = request.session.get('phone_num')
        try:
            # q = spi_User.objects.get(user_phone=phone)
            q = spi_User.objects.filter(user_phone=phone).last()
            p = q.spi_resume_set.get(user=q)
            p.resume_School = name
            p.resume_SchoolLevel = education
            p.resume_professional = major
            p.resume_GraduationTime = enddate
            p.save()
            response['school_case'] = 'ok'
        except:
            response['school_case'] = 'no'
    return JsonResponse(response)


# 检查手机号码, 邮箱是否在数据库中存在
# @csrf_exempt
def chk_phone(request):
    response = {}
    Account = ''
    if request.method == 'POST':
        result = json.loads(bytes.decode(request.body))
        Account = result.get('Account_num')
    rep = re.match(r"^1[35678]\d{9}$", Account)
    ree = re.findall(r'^\w+@(\w+.)+(com|cn|net)$', Account)

    if rep:
        try:
            a = spi_User.objects.get(user_phone=Account)
            response['login_case'] = 'ok'
        except:
            response['login_case'] = 'no'
    elif ree:
        try:
            a = spi_User.objects.get(user_mail=Account)
            response['login_case'] = 'ok'
        except:
            response['login_case'] = 'no'

    return JsonResponse(response)


# 发送手机验证码
def Send_phone(request):
    response = {}
    phone_num = None
    code = ''
    if request.method == 'POST':
        result = json.loads(bytes.decode(request.body))
        phone_num = result.get('phone_num')
        request.session['phone_num'] = phone_num
    if phone_num:
        # 生成验证码
        code = ComFunction.NumverCode()
        # 存入将验证码redis,并设置时效300s
        cache.set('phone_' + phone_num, code, 300)
        # 发送短信SendPhoneCode(phone,code)； phone:11位电话号码 ， code：验证码
        # ComFunction.SendPhoneCode(phone=phone_num, code=code)
        return JsonResponse({'send_case': 'on', 'code': code, })
    return JsonResponse({'send_case': 'off', })


# 找回密码
def retrievePwd(request):
    phone_code = ''
    phone_num = ''
    password = ''
    response = {}
    code = ''
    if request.method == 'POST':  # 接收参数
        result = json.loads(bytes.decode(request.body))
        phone_num = result.get('phone_num')
        password = result.get('password')
        phone_code = result.get('Verification_code')
        code = cache.get('phone_' + phone_num)
    if code == '':  # 验证码失效
        response['retrievePwd_case'] = '1'
        return JsonResponse(response)
    elif code != phone_code:  # 验证码有误
        response['retrievePwd_case'] = '2'
        return JsonResponse(response)
    try:
        a = spi_User.objects.get(user_phone=phone_num)
        a.user_password = make_password(password)
        a.save()
        response['retrievePwd_case'] = 'ok'
        return JsonResponse(response)
    except:  # 手机号码有误
        response['retrievePwd_case'] = '3'
        # messages.success(request, '手机号码有误')
        return JsonResponse(response)
